package stru1.day11;

import java.util.*;

/**
 * 102. 二叉树的层序遍历
 */
public class Solution1 {
    public static void main(String[] args) {
        System.out.println(levelOrder(new TreeNode(3, new TreeNode(9),
                new TreeNode(20, new TreeNode(15, null, null), new TreeNode(7, null, null)))));

        System.out.println(levelOrder(new TreeNode(1)));

        System.out.println(levelOrder(null));
    }

    /**
     * 利用队列实现层序遍历(DFS)
     * 时间复杂度 O(n)
     * 空间复杂度 O(n)
     */
    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ans = new LinkedList<>();
        if (root == null) return ans;

        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> currList = new ArrayList<>(size);
            for (int i = 0; i < size; i++) {
                TreeNode curr = queue.poll();
                assert curr != null;
                currList.add(curr.val);
                if (curr.left != null) queue.offer(curr.left);
                if (curr.right != null) queue.offer(curr.right);
            }
            ans.add(currList);
        }
        return ans;
    }
}
